package com.xjzd.std.concurrency;

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolDemo {

    private record Task(int code) implements Runnable {

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "-" + this.code);
            try {
                System.in.read();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public String toString() {
            return "Task{" +
                    "code=" + code +
                    '}';
        }
    }

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                3,
                5,
                5,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );

        for (int i = 0; i < 10; i++) {
            threadPoolExecutor.execute(new Task(i));
        }

        System.out.println("queue: " + threadPoolExecutor.getQueue());

        threadPoolExecutor.execute(new Task(100));

        System.out.println("queue: " + threadPoolExecutor.getQueue());

        threadPoolExecutor.shutdown();
    }
}
